'use strict';
var path = require('path');
var fs = require("fs");

function onBuildFinish (options, callback) {
	Editor.log('热更工具 Building ' + options.platform + ' to ' + options.dest); // 你可以在控制台输出点什么

	callback();
	// Editor.Ipc.sendToPanel('热更工具', '热更工具:build_finish',options);
	process.env.buildDest = options.dest;
	reWriteMainJS(options.dest);
}

function reWriteMainJS(outputDir){
	var inject_script = `
		(function () {
			if (typeof window.jsb === 'object') {
				var hotUpdateSearchPaths = localStorage.getItem('HotUpdateSearchPaths');
				if (hotUpdateSearchPaths) {
					var paths = JSON.parse(hotUpdateSearchPaths);
					jsb.fileUtils.setSearchPaths(paths);

					var fileList = [];
					var storagePath = paths[0] || '';
					var tempPath = storagePath + '_temp/';
					var baseOffset = tempPath.length;

					if (jsb.fileUtils.isDirectoryExist(tempPath) && !jsb.fileUtils.isFileExist(tempPath + 'project.manifest.temp')) {
						jsb.fileUtils.listFilesRecursively(tempPath, fileList);
						fileList.forEach(srcPath => {
							var relativePath = srcPath.substr(baseOffset);
							var dstPath = storagePath + relativePath;

							if (srcPath[srcPath.length] == '/') {
								cc.fileUtils.createDirectory(dstPath)
							}
							else {
								if (cc.fileUtils.isFileExist(dstPath)) {
									cc.fileUtils.removeFile(dstPath)
								}
								cc.fileUtils.renameFile(srcPath, dstPath);
							}
						})
						cc.fileUtils.removeDirectory(tempPath);
					}
				}
			}
		})();
	`;	
	
	var root = outputDir;    
    var url = path.join(root, "main.js");
	Editor.log("rootUrl",url);
    fs.readFile(url, "utf8", function (err, data) {
        if (err) {
            throw err;
        }

        var newStr = inject_script + data;
        fs.writeFile(url, newStr, function (error) {
            if (err) {
                throw err;
            }
            Editor.log("SearchPath updated in built main.js for hot update");
        });
    });
}

module.exports = {
  load () {
    // execute when package loaded
	
	Editor.Builder.on('build-finished', onBuildFinish);
  },

  unload () {
    // execute when package unloaded
	Editor.Builder.removeListener('build-finished', onBuildFinish);
  },

  // register your ipc messages here
  messages: {
    'open' () {
      // open entry panel registered in package.json
      Editor.Panel.open('native_hotupdate');
    },
    'say-hello' () {
      Editor.log('Hello World!');
      // send ipc message to panel
      Editor.Ipc.sendToPanel('native_hotupdate', 'native_hotupdate:hello');
    },
    'clicked' () {
      Editor.log('Button clicked!');
    }
  },
};